package com.veketor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

public class ProductSet {
	private Vector<Product> productSet;
	private String nameTable="PRODUCTS";
	protected String className="ProductSet";
	protected Vector<Product> ProductSubSet;
	
	ProductSet()
	{
		productSet = new Vector<Product>();
	}

	public void createTable()
	{//TODO seams that existTable do not work as expected.
		try
		{
			//if(!existTable())//TODO the problem is here.
			//{
				//Debug.out(6,"Table ["+nameTable+"] not found");
				DbManager.updTable("CREATE TABLE IF NOT EXISTS "+nameTable+" (id INTEGER PRIMARY KEY, name TEXT, price NUMERIC, stock NUMERIC, alarmStock NUMERIC, imgPath TEXT, date TEXT, tax Numeric, location Numeric)");
			//}
			//else
			//{
				//Debug.out(6,"Table ["+nameTable+"] not found");
			//}
		}
		catch (Exception e)
		{
			Debug.out(e);
		}	
	}
	
	protected boolean existTable()
	{//TODO: verify!!!
		boolean boResult=false;
		ResultSet rs=DbManager.getMetadata();
		String stResult="";
		try
		{
			while (rs.next() || !	boResult) 
			{
				stResult=rs.getString("TABLE_NAME").toString();
				if (stResult.equals(nameTable))
				{
					boResult=true;
					Debug.out("Encontrada");
				}
			}
			if (!boResult)
			{
				//createTable();
			}
		}
		catch (SQLException e)	{	Debug.out(e);  }
		catch (Exception e)	{	Debug.out(e);  }
		return boResult;
	}
	
	private void addProduct(Product newProduct)
	{
		try
		{
			productSet.add(newProduct);
		}
		catch (Exception e){Debug.out(e);}
	}

	
	public void loadTable()
	{
		ResultSet rs = DbManager.loadFromTable(nameTable);
		Product pro= new Product();
		try
		{
			while (rs.next())
			{
				pro.loadFromResulSet(rs);
				this.addProduct(pro);
			}
		}
		catch (SQLException e){Debug.out(e);}
		catch (Exception e){Debug.out(e);}
	}
	
	public Product getProductbyIndex(int index)
	{//TODO: return by ID on table, not by ID on Vector!!!!
		return productSet.get(index);
	}
}
